package zh.keep.all

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import androidx.core.app.NotificationManagerCompat
import zh.keep.all.services.ForegroundService
import zh.keep.all.services.LiveService

/**
 * 检查忽略电池优化
 */
fun Context.queryBatteryOptimizeStatus(): Boolean {
    val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager?
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        powerManager?.isIgnoringBatteryOptimizations(packageName) ?: false
    } else {
        true
    }
}

/**
 * 检查系统通知权限
 */
fun Context.notificationMonitor() {
    //监听通知
    if (NotificationManagerCompat.getEnabledListenerPackages(this).contains(packageName)) {
        val intent = Intent(this, LiveService::class.java)
        startService(intent)
    } else {
        startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
    }
}

/**
 * 忽略电池优化
 */
fun Context.requestIgnoreBatteryOptimizations() {
    try {
        val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
        intent.data = Uri.parse("package:$packageName")
        startActivity(intent)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

object Utils {

    fun startService() {
        val mForegroundService = Intent(MyApplication.myContext, ForegroundService::class.java)
        mForegroundService.putExtra("Foreground", "开启前台服务.");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            MyApplication.myContext.startForegroundService(mForegroundService)
        } else {
            MyApplication.myContext.startService(mForegroundService)
        }
    }

    fun cal(second: Int): String {
        var h = 0
        var d = 0
        var s = 0
        val temp = second % 3600
        if (second > 3600) {
            h = second / 3600
            if (temp != 0) {
                if (temp > 60) {
                    d = temp / 60
                    if (temp % 60 != 0) {
                        s = temp % 60
                    }
                } else {
                    s = temp
                }
            }
        } else {
            d = second / 60
            if (second % 60 != 0) {
                s = second % 60
            }
        }
        return h.toString() + "时" + d + "分" + s + "秒"
    }
}